<!-- 用户中心 -->
<template>
  <div>
    <wbc-nav></wbc-nav>
    <div class="container">
      <div v-show="isEdit" class="tcommonBox">
        <header>
          <h1>编辑个人资料</h1>
        </header>
        <section>
          <ul class="userInfoBox">
            <li class="avatarlist">
              <span class="leftTitle">头像：</span>
              <el-upload
                class="avatar-uploader"
                name="img"
                :action="uploadURL"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img
                  v-if="userInfoObj.avatar"
                  :src="
                    userInfoObj.avatar
                      ? userInfoObj.avatar
                      : 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
                  "
                  :onerror="$store.state.errorImg"
                  class="avatar"
                />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                <div slot="tip" class="el-upload__tip">
                  点击上传头像，只能上传jpg/png文件，且不超过1mb
                </div>
              </el-upload>
            </li>
            <li class="username">
              <span class="leftTitle">用户等级：</span>
              <span class="userVip">Lv.{{ userInfoObj.userVip }}</span>
            </li>
            <li class="username">
              <span class="leftTitle">用户UID：</span>
              <span class="user_uuid">{{
                userInfoObj.userUuid ? userInfoObj.userUuid : "无"
              }}</span>
            </li>
            <li class="username">
              <span class="leftTitle">用户会员：</span>
              <span
                class="userSvip"
                v-bind:class="{
                  normal: userSvipText === '普通用户',
                  vip: userSvipText === 'vip普通会员',
                  'super-vip': userSvipText === 'Svip超级会员',
                  'annual-vip': userSvipText === 'vip年费会员',
                  'annual-super-vip': userSvipText === 'Svip年费超级会员',
                }"
                ><svg class="icon huiyuan" aria-hidden="true">
                  <use xlink:href="#icon-huiyuan"></use>
                </svg>
                {{ userSvipText }}</span
              >
            </li>
            <li class="username">
              <span class="leftTitle">用户积分：</span>
              <span class="userExp"
                ><svg class="icon" aria-hidden="true">
                  <use xlink:href="#icon-jifen1"></use></svg
                >{{ userInfoObj.userExp }}</span
              >
            </li>
            <li class="username">
              <span class="leftTitle">用户昵称：</span>
              <el-input
                v-model="userInfoObj.nickName"
                placeholder="昵称"
              ></el-input>
              <i class="fa fa-wa fa-asterisk"></i>
            </li>
            <li class="username">
              <span class="leftTitle">电子邮件：</span>
              <el-input
                v-model="userInfoObj.email"
                placeholder="电子邮件"
              ></el-input>
              <i class="fa fa-wa fa-asterisk"></i>
            </li>
            <li class="username">
              <span class="leftTitle">手机号：</span>
              <el-input
                v-model="userInfoObj.phonenumber"
                placeholder="手机号"
              ></el-input>
              <i class="fa fa-wa fa-asterisk"></i>
            </li>
            <li>
              <span class="leftTitle">性别：</span>
              <template>
                <el-radio class="radio" v-model="userInfoObj.sex" label="0"
                  >男</el-radio
                >
                <el-radio class="radio" v-model="userInfoObj.sex" label="1"
                  >女</el-radio
                >
              </template>
            </li>
            <li>
              <span class="leftTitle">注册时间：</span>
              <span class="user_createTime">{{
                userInfoObj.registerTime ? userInfoObj.registerTime : "无"
              }}</span>
            </li>
          </ul>
          <div class="saveInfobtn">
            <a
              class="tcolors-bg"
              href="javascript:void(0);"
              @click="isEdit = !isEdit"
              >返 回</a
            >
            <a
              class="tcolors-bg"
              href="javascript:void(0);"
              @click="saveInfoFun"
              >保 存</a
            >
          </div>
        </section>
      </div>

      <div v-show="!isEdit" class="tcommonBox">
        <header>
          <h1>
            个人中心
            <el-button
              style="float: right; height: 40px"
              type="primary"
              icon="el-icon-edit"
              class="MobilePC"
              @click="isEdit = !isEdit"
              round
              >修改资料</el-button
            >
            <el-button
              style="float: right; height: 40px; margin-right: 10px"
              type="primary"
              icon="el-icon-lock"
              class="MobilePC"
              @click="updatePassword = true"
              round
              >修改密码</el-button
            >
            <!-- 移动按钮 -->
            <el-button
              style="float: right; height: 40px; width: 30%"
              type="primary"
              icon="el-icon-edit"
              class="Mobile"
              @click="isEdit = !isEdit"
              round
              >修改资料</el-button
            >
            <el-button
              style="float: right; height: 40px; width: 30%; margin-right: 5px"
              type="primary"
              icon="el-icon-lock"
              class="Mobile"
              @click="updatePassword = true"
              round
              >修改密码</el-button
            >
          </h1>
        </header>

        <section>
          <ul class="userInfoBox">
            <li class="avatarlist">
              <el-skeleton
                :loading="isLoading"
                animated
                :rows="3"
                style="width: 100%"
              >
                <span class="leftTitle">头像：</span>
                <div class="avatar-uploader">
                  <img
                    :src="
                      userInfoObj.avatar
                        ? userInfoObj.avatar
                        : 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
                    "
                    :onerror="$store.state.errorImg"
                    class="avatar"
                  />
                </div>
              </el-skeleton>
            </li>
            <li class="username">
              <el-skeleton
                :loading="isLoading"
                animated
                :rows="3"
                style="width: 100%"
              >
                <span class="leftTitle">用户等级：</span>
                <span class="userVip"
                  ><svg class="icon huiyuan" aria-hidden="true">
                    <use xlink:href="#icon-dengjizhongxin"></use></svg
                  >Lv.{{ userInfoObj.userVip }}</span
                >
              </el-skeleton>
            </li>
            <li class="username">
              <el-skeleton
                :loading="isLoading"
                animated
                :rows="3"
                style="width: 100%"
              >
                <span class="leftTitle">用户UID：</span>
                <span class="user_uuid">{{
                  userInfoObj.userUuid ? userInfoObj.userUuid : "无"
                }}</span>
              </el-skeleton>
            </li>
            <li class="username">
              <el-skeleton
                :loading="isLoading"
                animated
                :rows="3"
                style="width: 100%"
              >
                <span class="leftTitle">用户会员：</span>

                <span
                  class="userSvip"
                  v-bind:class="{
                    normal: userSvipText === '普通用户',
                    vip: userSvipText === 'vip普通会员',
                    'super-vip': userSvipText === 'Svip超级会员',
                    'annual-vip': userSvipText === 'vip年费会员',
                    'annual-super-vip': userSvipText === 'Svip年费超级会员',
                  }"
                >
                  <svg class="icon huiyuan" aria-hidden="true">
                    <use xlink:href="#icon-huiyuan"></use>
                  </svg>
                  {{ userSvipText }}</span
                >

                <el-button
                  type="primary"
                  class="custom-button"
                  style="background-color: #409eff; border: 2px solid #409eff"
                  @click="dialogVisible = true"
                  >兑换会员</el-button
                >
                <span class="viptime"
                  >会员到期时间：{{
                    userInfoObj.sviptime ? userInfoObj.sviptime : "无"
                  }}</span
                >

                <!-- 移动兑换会员界面 -->
                <div v-if="dialogVisible" class="duihuansmall">
                  <h4>兑换会员</h4>

                  <div>
                    <input
                      type="radio"
                      id="membership1"
                      v-model="selectedMembership"
                      value="1"
                    />
                    <label for="membership1">兑换30天普通会员(5000积分)</label>
                  </div>

                  <div class="dialog-footer">
                    <button @click="dialogVisible = false">取消</button>
                    <button type="button" @click="exchangeMembership">
                      确定
                    </button>
                  </div>
                </div>
              </el-skeleton>
            </li>
            <li class="username">
              <el-skeleton
                :loading="isLoading"
                animated
                :rows="3"
                style="width: 100%"
              >
                <span class="leftTitle">用户积分：</span>
                <span class="userExp">
                  <svg class="icon" aria-hidden="true">
                    <use xlink:href="#icon-jifen1"></use>
                  </svg>
                  {{ userInfoObj.userExp ? userInfoObj.userExp : "无" }}</span
                >
                <el-button
                  type="warning"
                  class="custom-button"
                  @click="signIn"
                  >{{
                    userInfoObj.userSign === "0"
                      ? "未签到"
                      : userInfoObj.userSign === "1"
                      ? "已签到"
                      : userInfoObj.userSign || "无"
                  }}</el-button
                >
              </el-skeleton>
            </li>
            <li class="username">
              <el-skeleton
                :loading="isLoading"
                animated
                :rows="3"
                style="width: 100%"
              >
                <span class="leftTitle">用户昵称：</span>
                <span class="user_name">{{
                  userInfoObj.nickName ? userInfoObj.nickName : "无"
                }}</span>
              </el-skeleton>
            </li>
            <li>
              <el-skeleton
                :loading="isLoading"
                animated
                :rows="3"
                style="width: 100%"
              >
                <span class="leftTitle">电子邮件：</span>
                <span class="user_email">{{
                  userInfoObj.email ? userInfoObj.email : "无"
                }}</span>
              </el-skeleton>
            </li>
            <li>
              <el-skeleton
                :loading="isLoading"
                animated
                :rows="3"
                style="width: 100%"
              >
                <span class="leftTitle">手机号：</span>
                <span class="user_phone">{{
                  userInfoObj.phonenumber ? userInfoObj.phonenumber : "无"
                }}</span>
              </el-skeleton>
            </li>
            <li>
              <el-skeleton
                :loading="isLoading"
                animated
                :rows="3"
                style="width: 100%"
              >
                <span class="leftTitle">性别：</span>
                <span class="user_sex">{{
                  userInfoObj.sex == 0 ? "男" : "女"
                }}</span>
              </el-skeleton>
            </li>
            <li>
              <el-skeleton
                :loading="isLoading"
                animated
                :rows="3"
                style="width: 100%"
              >
                <span class="leftTitle">注册时间：</span>
                <span class="user_createTime">{{
                  userInfoObj.registerTime ? userInfoObj.registerTime : "无"
                }}</span>
              </el-skeleton>
            </li>
          </ul>
        </section>
      </div>
    </div>
    <el-dialog
      title="修改密码"
      :visible.sync="updatePassword"
      width="30%"
      center
    >
      <!-- Use el-form to wrap the input fields -->
      <el-form
        ref="passwordForm"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="100px"
      >
        <el-form-item label="新密码" prop="password">
          <el-input
            v-model="passwordForm.password"
            type="password"
            auto-complete="off"
            show-password
            :prefix-icon="blueIconClass"
          ></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            auto-complete="off"
            show-password
            :prefix-icon="blueIconClass"
          ></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button
          @click="handleCancelPassword"
          style="width: 80px; height: 40px"
        >
          取 消
        </el-button>
        <el-button
          type="primary"
          style="width: 80px; height: 40px"
          @click="handleSubmit"
        >
          确 定
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import header from "../components/header.vue";
import {
  getUserInfo,
  savaUserInfo,
  saveuserexp,
  exchangevip,
  updatePassword,
} from "../api/user.js"; //获取用户信息，保存用户信息

import store from "../store";
export default {
  name: "UserInfo",
  data() {
    //选项 / 数据
    return {
      isLoading: true,
      updatePassword: false,
      blueIconClass: "el-icon-lock", // 图标类名
      id: "",
      passwordForm: {
        password: "",
        confirmPassword: "",
      },
      passwordRules: {
        password: [
          { required: true, message: "请输入新密码", trigger: "blur" },
          // Add any other password validation rules here
        ],
        confirmPassword: [
          { required: true, message: "请确认密码", trigger: "blur" },
          { validator: this.validateConfirmPassword, trigger: "blur" },
        ],
      },

      uploadURL: "",
      isEdit: false,
      userInfo: {}, //本地存储的用户信
      userInfoObj: "", //用户的信息
      isSigned: false, // 初始化为未签到状态
      dialogVisible: false,
      isTenDays: false,
      selectedMembership: 1,
    };
  },
  methods: {
    validateConfirmPassword(rule, value, callback) {
      if (value !== this.passwordForm.password) {
        callback(new Error("两次输入的密码不一致"));
      } else {
        callback();
      }
    },
    handleCancelPassword() {
      this.$refs.passwordForm.resetFields(); // Reset form fields
      this.updatePassword = false; // Close dialog
    },
    handleSubmit() {
      var that = this;
      this.$refs.passwordForm.validate((valid) => {
        if (valid) {
          var id = that.userId; // 使用 userId
          var password = this.passwordForm.password;
          updatePassword(id, password).then((response) => {
            this.$message.success("修改密码成功");
            that.handleCancelPassword();
            location.reload(); // 刷新页面
          });
        } else {
        }
      });
    },

    handleClose(done) {
      // 关闭对话框前的逻辑处理，如果需要的话
      done();
    },

    exchangeMembership() {
      const requiredExp = this.selectedMembership === 1 ? 5000 : 15000;
      if (this.userInfoObj.userExp >= requiredExp) {
        // 用户积分足够，执行兑换会员的逻辑
        if (this.selectedMembership === 1) {
          // 兑换30天普通会员逻辑
          exchangevip(this.userInfoObj).then((response) => {
            //判断是否满足？
            this.$message.success("兑换成功一个月");
          });
          setTimeout(() => {
            location.reload(); // 或者使用 this.$router.push({ path: '/' }) 来跳转到当前页面
          }, 2000);
        } else if (this.selectedMembership === 2) {
          // 兑换30天超级会员逻辑
        }
      } else {
        // 用户积分不足，进行相应的提示或处理逻辑
        this.$message.error("用户积分不足");
        // 刷新页面
        setTimeout(() => {
          location.reload(); // 或者使用 this.$router.push({ path: '/' }) 来跳转到当前页面
        }, 1000);
      }

      this.dialogVisible = false; // 关闭对话框
      this.selectedMembership = null; // 重置选项
    },

    //事件处理器
    handleAvatarSuccess(res, file) {
      //上传头像
      if (res.code == 200) {
        this.userInfoObj.avatar = res.data;
        this.userInfoObj.head_start = 1;
        this.$message.success("上传成功");
      } else {
        this.$message.error("上传图片失败");
      }
    },
    beforeAvatarUpload(file) {
      //判断头像大小
      const isJPG =
        file.type == "image/png" ||
        file.type == "image/jpg" ||
        file.type == "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 1;
      // console.log(file);
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG/JPEG/PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 1MB!");
      }
      return isJPG && isLt2M;
    },

    saveInfoFun: function () {
      //保存编辑的用户信息
      var that = this;

      if (!that.userInfoObj.nickName) {
        //昵称为必填
        that.$message.error("昵称为必填项，请填写昵称");
        return;
      }

      savaUserInfo(that.userInfoObj).then((response) => {
        //保存信息接口，返回展示页
        that.$message.success("保存成功！");
        that.isEdit = false;
        that.routeChange();
      });
    },
    routeChange: function () {
      var that = this;

      if (localStorage.getItem("userInfo")) {
        that.haslogin = true;
        that.userInfo = JSON.parse(localStorage.getItem("userInfo"));
        that.userId = that.userInfo.id;

        getUserInfo(that.userId).then((response) => {
          that.userInfoObj = response;
          that.userInfoObj.head_start = 0;

          // 延迟两秒后关闭 Loading
          setTimeout(() => {
            this.isLoading = false;
          }, 2000);
        });
      } else {
        that.haslogin = false;
      }
    },
    signIn() {
      var that = this;
      // 处理签到逻辑，例如增加经验值等
      saveuserexp(that.userInfoObj).then((response) => {
        that.$message.success("签到成功！积分+1000");

        // 延迟三秒后刷新当前页面
        setTimeout(() => {
          location.reload(); // 或者使用 this.$router.push({ path: '/' }) 来跳转到当前页面
        }, 1000); // 3000毫秒等于三秒
      });

      // 设置签到状态为已签到
      this.isSigned = true;
    },
  },
  components: {
    //定义组件
    "wbc-nav": header,
  },
  watch: {
    // 如果路由有变化，会再次执行该方法
    $route: "routeChange",
  },
  created() {
    //生命周期函数
    this.routeChange();
    this.uploadURL = store.state.baseURL + "upload";
  },
  computed: {
    userSvipText() {
      // 将 userSvip 的值映射到中文字符串
      switch (this.userInfoObj.userSvip) {
        case "0":
          return "普通用户";
        case "1":
          return "vip普通会员";
        case "2":
          return "Svip超级会员";
        case "3":
          return "vip年费会员";
        case "4":
          return "Svip年费超级会员";
        default:
          return "未知"; // 如果值无法匹配任何情况，返回 '未知'
      }
    },
  },
};
</script>

<style scoped>
.userVipskeleton{
  width: 100%;
}
.custom-button {
  font-size: 16px; /* 按钮字体大小 */
  padding: 4px 8px; /* 按钮内边距，上下10px，左右20px */
  border: 2px solid #ff4500; /* 边框样式，这里使用橙红色边框 */
  border-radius: 5px; /* 圆角边框 */
  background-color: #ff4500; /* 按钮背景颜色，这里使用橙红色 */
  color: #fff; /* 按钮文本颜色，白色 */
}
@media (max-width: 767px) {
  .duihuansmall {
    width: 100% !important;
    text-align: center;
    font-weight: bold;
  }

  .MobilePC {
    display: none;
  }
  .Mobile {
    font-size: 0.5rem;
  }
}
@media (min-width: 769px) {
  .duihuansmall {
    width: 50% !important;
    display: block;
    margin-left: 20%;
    text-align: center;
    font-weight: bold;
  }
  .Mobile {
    display: none;
  }
}
</style>

<style>
.el-input__prefix {
  color: #409eff; /* 浅蓝色图标颜色 */
}
.username .user_uuid {
  font-weight: bold;
  font-size: 1.2rem;
  font-family: Arial, sans-serif;
  /* 其他字体属性设置 */
  font-weight: bold;
  color: #606266;
}

@media (max-width: 767px) {
  .el-dialog {
    width: 90% !important;
  }
}

.icon {
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}

/* 添加流光字体效果 */
@keyframes glowing {
  0% {
    text-shadow: 0 0 10px rgba(154, 230, 56, 0.8);
  }
  50% {
    text-shadow: 0 0 20px rgba(26, 233, 129, 0.8);
  }
  100% {
    text-shadow: 0 0 10px rgba(255, 255, 255, 0.8);
  }
}
/* vip */
.duihuan {
  text-align: center;
  font-weight: bold;
}
.duihuan .el-dialog {
  border-radius: 8px;
}

.checkbox-item {
  margin-bottom: 10px;
}
.userInfoBox .avatarlist {
  position: relative;
}
.leftTitle {
  font-weight: bold;
}
.userVip {
  font-size: 1.2rem;
  font-weight: bold;
  color: #f57914;
}
.userSvip {
  font-weight: bold; /* 加粗文本 */
}
.normal {
  /* 普通用户的样式 */
  color: rgb(121, 121, 121);
  /* 其他样式属性 */
}

.vip {
  /* 普通会员的样式 */
  color: #20bae9;
  /* 其他样式属性 */
}

.super-vip {
  /* 超级会员的样式 */
  color: #ff0000;
  /* 其他样式属性 */
}

.annual-vip {
  /* 年费会员的样式 */
  color: #ff5100;
  /* 其他样式属性 */
}

.annual-super-vip {
  /* 年费超级会员的样式 */
  color: #e22794;
  /* 其他样式属性 */
  animation: glowing 3s infinite;
}
.viptime {
  color: #999;
}

.user_name {
  font-weight: bold; /* 加粗 */
  font-size: 1rem; /* 字体大小 */
  color: #007bff; /* 设置文本颜色，这里使用蓝色 */
  text-decoration: underline; /* 添加下划线文本装饰 */
}
.user_email {
  font-weight: normal; /* 可以根据需要调整字体粗细 */
  font-size: 14px; /* 字体大小，可以根据需要调整 */
  color: #333; /* 设置文本颜色，这里使用深灰色 */
  /* 如果不需要文本装饰（如下划线），可以删除下面这一行 */
  text-decoration: underline; /* 添加下划线文本装饰 */
}
.user_phone {
  font-weight: normal; /* 可以根据需要调整字体粗细 */
  font-size: 14px; /* 字体大小，可以根据需要调整 */
  color: #333; /* 设置文本颜色，这里使用深灰色 */
  /* 如果不需要文本装饰（如下划线），可以删除下面这一行 */
  text-decoration: none; /* 移除下划线文本装饰 */
}
.user_sex {
  font-weight: normal; /* 可以根据需要调整字体粗细 */
  font-size: 14px; /* 字体大小，可以根据需要调整 */
  color: #333; /* 设置文本颜色，这里使用深灰色 */
}
.userExp {
  font-weight: bold; /* 加粗 */
  font-size: 16px; /* 字体大小，可以根据需要调整 */
  color: #ffffff; /* 设置文本颜色，这里使用白色 */
  background-color: #00e1ff; /* 设置背景颜色，这里使用蓝色 */
  padding: 5px 10px; /* 添加内边距，使文本更突出 */
  border-radius: 5px; /* 圆角边框 */
}
/* 自定义按钮样式 */

.avatar-uploader {
  display: inline-block;
  vertical-align: top;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 120px;
  height: 120px;
}
.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
  position: absolute;
  top: 0;
  left: 0;
}
.avatar {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  display: block;
  object-fit: cover;
}
.gotoEdit {
  font-size: 15px;
  float: right;
  cursor: pointer;
  color: #999;
}
.gotoEdit:hover {
  color: #333;
}
/*个人设置*/
.userInfoBox .leftTitle {
  display: inline-block;
  width: 100px;
  padding: 10px 0;
}
.userInfoBox .rightInner {
  display: inline-block;
  max-width: calc(100% - 140px);
  vertical-align: top;
}
.userInfoBox li {
  padding: 20px;
  border-bottom: 1px solid #ddd;
}
.userInfoBox li:last-child {
  border-bottom: 1px solid transparent;
}
.userInfoBox .el-input,
.userInfoBox .el-textarea {
  max-width: 300px;
  min-width: 100px;
}

.userInfoBox .el-input__inner {
  border-radius: 4px;
}
.userInfoBox .el-textarea {
  vertical-align: top;
}
.saveInfobtn {
  margin: 20px 0;
  text-align: center;
}
.saveInfobtn a {
  color: #fff;
  padding: 6px 20px;
  margin: 5px 10px;
  border-radius: 5px;
  font-size: 14px;
}
.userInfoBox .fa-asterisk {
  color: #df2050;
}
</style>
